package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"moon-exam-sys/cache"
	"moon-exam-sys/models"
	"moon-exam-sys/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	redis_key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}
	var user models.User
	models.DB.Where("username=?", username).First(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := models.UserRole{
		Uid: uid,
		Rid: rid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func RoleNodeAdd(c *gin.Context) {

	nid, _ := strconv.Atoi(c.PostForm("nid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := models.RoleNode{
		Nid: nid,
		Rid: rid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func UserRoleList(c *gin.Context) {

	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.rid
		WHERE
		  user_roles.uid = 1
	*/
	uid, _ := strconv.Atoi(c.Query("uid"))

	var role []models.Role
	models.DB.Table("roles").Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
		Where("user_roles.uid=?", uid).Debug().
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": role,
	})
}
func RoleNodeList(c *gin.Context) {

	/*
			SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE
		  role_nodes.rid = 1
	*/
	rid, _ := strconv.Atoi(c.Query("rid"))

	var node []models.Node
	models.DB.Table("nodes").Joins(" LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid=?", rid).Debug().
		Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": node,
	})
}
func CarAdd(c *gin.Context) {
	carcode := c.PostForm("carcode")
	carname := c.PostForm("carname")
	carnum := c.PostForm("carnum")
	data := models.Car{
		CarCode: carcode,
		CarName: carname,
		CarNum:  carnum,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderAdd(c *gin.Context) {
	orderno := c.PostForm("orderno")
	fromaddress := c.PostForm("fromaddress")
	toaddress := c.PostForm("toaddress")
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	data := models.Order{
		OrderNo:     orderno,
		FromAddress: fromaddress,
		ToAddress:   toaddress,
		Cid:         cid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

//	func OrderList(c *gin.Context) {
//		page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
//		size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
//		offset := (page - 1) * size
//		/*
//			SELECT
//			  orders.id AS OrderID,
//			  orders.order_no AS OrderNo,
//			  orders.from_address AS FromAddress,
//			  orders.to_address AS ToAddress,
//			  cars.car_code AS CarCode,
//			  cars.car_name AS CarName,
//			  cars.car_num AS CarNum
//			FROM
//			  orders
//			  LEFT JOIN cars ON cars.id = orders.cid
//		*/
//		var orderList []models.OrderList
//		redis_key := "list_" + strconv.Itoa(page)
//		cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
//		if cacheData == "" {
//			models.DB.Table("orders").
//				Select("orders.id AS OrderID",
//					"orders.order_no AS OrderNo",
//					"orders.from_address AS FromAddress",
//					"orders.to_address AS ToAddress",
//					"cars.car_code AS CarCode",
//					"cars.car_name AS CarName",
//					"cars.car_num AS CarNum").
//				Joins(" LEFT JOIN cars ON cars.id = orders.cid").
//				Offset(offset).Limit(size).Find(&orderList)
//			jsonData, _ := json.Marshal(orderList)
//			cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
//		} else {
//			json.Unmarshal([]byte(cacheData), &orderList)
//		}
//		var total int64
//		models.DB.Model(&models.Order{}).Count(&total)
//		c.JSON(200, gin.H{
//			"code":  200,
//			"msg":   "ok",
//			"data":  orderList,
//			"total": total,
//		})
//
// }
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	/*
		SELECT
		  orders.id as OrderID,
		  orders.order_no as  OrderNo,
		  orders.from_address as FromAddress,
		  orders.to_address as ToAddress,
		  cars.car_code as CarCode,
		  cars.car_name as CarName,
		  cars.car_num as CarNum
		FROM
		  orders
		  LEFT JOIN cars ON orders.cid = cars.id
	*/
	var orderlist []models.OrderList
	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Select("orders.id as OrderID",
				"orders.order_no as  OrderNo",
				"orders.from_address as FromAddress",
				"orders.to_address as ToAddress",
				"cars.car_code as CarCode",
				"cars.car_name as CarName",
				"cars.car_num as CarNum").
			Joins(" LEFT JOIN cars ON orders.cid = cars.id").
			Offset(offset).Limit(size).Find(&orderlist)
		jsonData, _ := json.Marshal(orderlist)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderlist)
	}
	var total int64
	models.DB.Table("orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  orderlist,
		"total": total,
	})
}
func OrderDetail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	/*
		SELECT
		  orders.id as OrderID,
		  orders.order_no as  OrderNo,
		  orders.from_address as FromAddress,
		  orders.to_address as ToAddress,
		  cars.car_code as CarCode,
		  cars.car_name as CarName,
		  cars.car_num as CarNum
		FROM
		  orders
		  LEFT JOIN cars ON orders.cid = cars.id
	*/
	var orderlist []models.OrderList
	redis_key := "list_" + strconv.Itoa(id)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Select("orders.id as OrderID",
				"orders.order_no as  OrderNo",
				"orders.from_address as FromAddress",
				"orders.to_address as ToAddress",
				"cars.car_code as CarCode",
				"cars.car_name as CarName",
				"cars.car_num as CarNum").
			Joins(" LEFT JOIN cars ON orders.cid = cars.id").
			Where("orders.id=?", id).
			Find(&orderlist)
		jsonData, _ := json.Marshal(orderlist)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderlist)
	}
	var total int64
	models.DB.Table("orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  orderlist,
		"total": total,
	})
}
